package com.ezhuan.common.dao.impl;

import java.util.List;
import java.util.Map;

import com.ezhuan.common.dao.IBaseDao;
import com.ezhuan.common.pojo.BasePojo;
import com.ezhuan.common.util.PageInfoUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

/**
 * Dao的实现类的父类
 * 
 * @author wangshSxt
 *
 */
public abstract class BaseDaoImpl<T> implements IBaseDao<T>
{
	@Override
	public boolean save(T t)
	{
		if (t instanceof BasePojo)
		{
			BasePojo basePojo = (BasePojo) t;
			Record record = basePojo.toRecord();
			/* 为了获取主键,先把id的值移除 */
			record.remove("id");
			boolean flag = Db.save(basePojo.getTableName(), "id", record);
			basePojo.setId(Integer.valueOf(record.get("id") + ""));
			return flag;
		}
		return false;
	}

	@Override
	public boolean update(T t)
	{
		if (t instanceof BasePojo)
		{
			BasePojo basePojo = (BasePojo) t;
			Record record = basePojo.toRecord();
			return Db.update(basePojo.getTableName(), record);
		}
		return false;
	}

	@Override
	public abstract T findOneDao(Map<String, Object> condMap);

	@Override
	public abstract List<T> findCondListDao(PageInfoUtil pageInfoUtil, Map<String, Object> condMap);
	
	/**
	 * 分页查询数据
	 * @param pageInfoUtil
	 * @param sql
	 * @param paramsList
	 * @return
	 */
	public List<Record> findByPage(PageInfoUtil pageInfoUtil , String sql,List<Object> paramsList)
	{
		/* 先计算总记录数 */
		String countSql = "select count(*) as totalCount " ; 
		String fromIndex = "from" ; 
		String orderIndex = "order by";
		if(sql.indexOf(orderIndex) != -1)
		{
			countSql += sql.substring(sql.indexOf(fromIndex), sql.indexOf(orderIndex));
		}else
		{
			countSql += sql.substring(sql.indexOf(fromIndex), sql.length());
		}
		Record record = Db.findFirst(countSql, paramsList.toArray());
		pageInfoUtil.setTotalRecord(Integer.valueOf(record.get("totalCount") + ""));
		
		/* 查询数据 */
		sql +="limit ? , ? ";
		paramsList.add(pageInfoUtil.getCurrentRecord());
		paramsList.add(pageInfoUtil.getPageSize());
		return Db.find(sql, paramsList.toArray());
	}
	
	/**
	 * 查询数据
	 * @param pageInfoUtil
	 * @param sql
	 * @param paramsList
	 * @return
	 */
	public List<Record> find(String sql,List<Object> paramsList)
	{
		/* 先计算总记录数 */
		return Db.find(sql, paramsList);
	}

}
